package com.qiche.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.config.YmlConfig;
import com.qiche.dto.MemberCardItemDto;
import com.qiche.enums.ResultEnum;
import com.qiche.exception.MySystemException;
import com.qiche.mapper.*;
import com.qiche.mapper2.Card2Mapper;
import com.qiche.model.*;
import com.qiche.service.CardService;
import com.qiche.service.VoucherService;
import com.qiche.service2.Card2Service;
import com.qiche.util.AliyunSmsUtils;
import com.qiche.util.ApplicationUtils;
import com.qiche.util.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * 卡券服务层
 *
 * @author Linzewen
 * <p>
 * 2018年2月27日
 */
@Service("cardService")
public class CardServiceImpl extends BaseService<Card> implements CardService {

    @Autowired
    private CardMapper cardMapper;

    @Autowired
    private Card2Service card2Service;

    @Autowired
    private GiftPackageMapper giftPackageMapper;

    @Autowired
    private MerchantMapper merchantMapper;


    @Autowired
    private CardLinkMapper cardLinkMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RegionWelfareMapper welfareMapper;

    @Autowired
    private Card2Mapper card2Mapper;

    @Autowired
    private StoreMemberMapper storeMemberMapper;

    @Autowired
    private VoucherService voucherService;
    @Autowired
    private YmlConfig ymlConfig;

    private Logger logger = LoggerFactory.getLogger(CardServiceImpl.class);

    @Override
    public PageInfo<Card> selectByPage(Card card, int page, int limit) {
        // int page = start / length + 1;
        Example example = new Example(Card.class);
        Example.Criteria criteria = example.createCriteria();
        if (card.getMerchantId() != null && card.getMerchantId() != 0) {
            criteria.andEqualTo("merchantId", card.getMerchantId());
        }
        if (card.getStatus() != null && !"".equals(card.getStatus())) {
            criteria.andEqualTo("status", card.getStatus());
        }
        if (card.getCustomerPhone() != null && !"".equals(card.getCustomerPhone())) {
            criteria.andLike("memberPhone", "%" + card.getCustomerPhone() + "%");
        }
        // 分页查询
        PageHelper.startPage(page, limit);
        List<Card> cardList = selectByExample(example);
        return new PageInfo<>(cardList);
    }


    @Override
    public int batchInsert(List<Card> cardList) {
        return cardMapper.insertList(cardList);
    }

    @Override
    public Card selectById(Long cardId) {
        Example example = new Example(Card.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", cardId);
        List<Card> cardList = selectByExample(example);
        if (cardList.size() > 0) {
            return cardList.get(0);
        }
        return null;
    }

    @Override
    public Card selectByCardcode(String cardCode) {
        Example example = new Example(Card.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("cardCode", cardCode);
        List<Card> cardList = selectByExample(example);
        if (cardList.size() > 0) {
            return cardList.get(0);
        }
        return null;
    }

    @Override
    public List<Card> selectByCustomerId(Long customerId) {
        Example example = new Example(Card.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("customerId", customerId);
        List<Card> cardList = selectByExample(example);
        return cardList;
    }

    @Override
    @Transactional
    public Result<?> isUsed(String cardCode) throws Exception {

        logger.info("进入核销流程");
        //需求变更，整合代金券的核销
        if (cardCode.length() == 25) {
            logger.info("代金券");
            return voucherService.verify(cardCode);
        } else if (cardCode.startsWith(ymlConfig.getQicheSystemCardPrefix())) {
            // 需求变更，整合人保的核销入口
            // 通过配置文件获取汽车门店券的特有标识
            // 汽车系统
            User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
            Card card = selectByCardcode(cardCode);
            if (card == null) {
                return Result.createByResultEnum(ResultEnum.CARD_NOT_EXIST);
            }
            Long merchantId = card.getMerchantId();
            if (currentUser.getMerchantId().longValue() != merchantId.intValue()) {
                return Result.createByResultEnum(ResultEnum.CARD_NOT_LOCAL_USE);
            }
            if ("2".equals(card.getStatus())) {
                return Result.createByResultEnum(ResultEnum.CARD_HAS_USED);
            }
            Date currentTime = new Date();
            if (!(card.getVerifyBeginDate().getTime() <= currentTime.getTime()
                    && card.getVerifyEndDate().getTime() >= currentTime.getTime())) {
                return Result.createByResultEnum(ResultEnum.CARD_NOT_TIME_VALIABLE);
            }
            boolean isOk = false;
            try {
                //------更新卡券数据库的数据Begin
               /* Example example = new Example(Card2.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("cardCode", cardCode);

                List<Card2> c2List = card2Mapper.selectByExample(example);
                if (c2List != null && c2List.size() > 0) {
                    Card2 card2 = c2List.get(0);
                    card2.setStatus("2");
                    isOk = card2Mapper.updateByPrimaryKeySelective(card2) > 0 ? true : false;
                }*/
                //------更新卡券数据库的数据End
                card.setStatus("2");
                card.setIsWriteoff(1);
                card.setWriteoffDate(new Date());
                cardMapper.updateByPrimaryKeySelective(card);
                return Result.createByResultEnum(ResultEnum.VERIFY_SUCCESS);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return Result.createByResultEnum(ResultEnum.VERIFY_FAILURE);
            }
        } else {
            logger.info("核销的券是人保券");
            User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
            // 当前登录用户为 智慧汽车账号 ，核销人保券需要授权
            Integer merchantId = currentUser.getMerchantId();
            Merchant merchant = merchantMapper.selectByPrimaryKey(merchantId.longValue());
            if (merchant.getPiccMid() == null || merchant.getPiccMid() == 0) {
                return Result.createByResultEnum(ResultEnum.UNAUTHORIZED_OPERATION);
            }
            Map<String, Object> result = card2Service.isUsed(cardCode, null, merchant.getPiccMid());
            if ((int) (result.get("code")) == 1) {
                return Result.createBySuccess(result.get("msg").toString(), "PICC");
            } else {
                return Result.createByErrorMessage(result.get("msg").toString());
            }
        }

    }

    @Override
    public List<Card> selectCardAmountAllByMerchantId(Integer merchantId) {
        Example example = new Example(Card.class);
        //  example.selectProperties("id,cardAmount,writeoffDate");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantId", merchantId);
        criteria.andEqualTo("status", 2);
        return selectByExample(example);
    }

    @Override
    public List<MemberCardItemDto> selectMemberCardDtoByMrchantId(Long merchantId, String memberPhone, String sortMoney) {


        return cardMapper.selectMemberCardDtoByMrchantId(merchantId, memberPhone, sortMoney);
    }

    @Override
    @Transactional
    public Result<?> postCard(Long packId) {
        // 这里要判断是不是重复发包 ,无保单的则不做限制
        GiftPackage pack = giftPackageMapper.selectByPrimaryKey(packId);
        Map<String, Integer> smsInfoMap = new HashMap<>();
        if (pack != null && pack.getPolicyId() != 0) {
            // 有保单号的限制重复发包
            if (pack.getStatus() != null && pack.getStatus() == 1) {
                throw new MySystemException(ResultEnum.PACKAGE_HAS_POSTED);
            }
        }
        // 对于无保单的 memerId和policyId已经不能唯一确定
        User currentUser = UserUtils.getCurrentUser();
        Merchant currentMerchant = merchantMapper.selectByPrimaryKey(currentUser.getMerchantId().longValue());

        StoreMember storeMember = storeMemberMapper.selectByPrimaryKey(pack.getOwnerId());
        // 根据packId找到对应的link
        Example example = new Example(CardLink.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("packId", packId);
        List<CardLink> links = cardLinkMapper.selectByExample(example);

        List<Card2> toSends = new ArrayList<>();
        // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();

        for (CardLink cardLink : links) {
            // calendar.setTime(new Date()); // 每次循环时间都要复位
            Product product = productMapper.selectByPrimaryKey(cardLink.getProductId());
            RegionWelfare welfare = welfareMapper.selectByPrimaryKey(cardLink.getWelfareId());
            // 根据每种产品的数量 循环
            //有智慧门店入口，不再维护卡券系统的入口
            for (int i = 0; i < cardLink.getCount(); i++) {
                calendar.setTime(new Date()); // 每次循环时间都要复位
                Card2 pCard = new Card2();
                pCard.setCardCode(ymlConfig.getQicheSystemCardPrefix() + ApplicationUtils.getRandomString(16));
                pCard.setActivityId(null);
                pCard.setAvailable("周一,周二,周三,周四,周五,周六,周日");
                if (product != null) {
                    pCard.setCardAmount(product.getPrice().longValue());
                    pCard.setCardTitle(product.getName());
                    pCard.setGetAmount(product.getPrice().longValue());
                }
                if (welfare != null) {
                    pCard.setCardAmount(welfare.getWelfarePrice().longValue());
                    pCard.setCardTitle(welfare.getWelfareName());
                    pCard.setGetAmount(welfare.getWelfarePrice().longValue());
                }
                pCard.setCardType("service");
                pCard.setMerchantName(currentMerchant.getName()); // 填店名
                pCard.setMerchantIntroduction(currentMerchant.getAddress()); // 填地址
                pCard.setStatus("1");
                pCard.setVerifyBeginDate(new Date()); // 当前时间为可核销开始时间
                calendar.add(Calendar.YEAR, cardLink.getUsePeriod());// 根据产品的有效期来定
                pCard.setVerifyEndDate(calendar.getTime());

                pCard.setCreateDate(new Date());
                pCard.setReceivingDate(new Date());
                // 设置ownerPhone 卡券系统根据该字段认领
                pCard.setOwnerPhone(storeMember.getPhone());
                toSends.add(pCard);
            }
        }

        smsInfoMap.put(storeMember.getPhone(), toSends.size());

        List<Card> cardList = new ArrayList<>();
        for (Card2 piccCard : toSends) {
            Card card = new Card();  //汽车系统的卡券
            card.setCardCode(piccCard.getCardCode());
            card.setCardType(piccCard.getCardType());
            card.setCreateDate(new Date());
            card.setStatus("1");
            card.setCardAmount(piccCard.getCardAmount().longValue());
            card.setCustomerId(pack.getOwnerId());
            card.setCustomerName(storeMember.getName());
            card.setCustomerPhone(storeMember.getPhone());
            card.setCardTitle(piccCard.getCardTitle());
            card.setAvailable(piccCard.getAvailable());
            card.setIsWriteoff(0); // 1：已核销 2：未核销
            card.setWriteoffDate(null);
            card.setVerifyBeginDate(piccCard.getVerifyBeginDate());
            card.setVerifyEndDate(piccCard.getVerifyEndDate());
            card.setMerchantId(currentUser.getMerchantId().longValue());
            card.setPackId(pack.getId());
            card.setPolicyId(pack.getPolicyId());
            cardList.add(card);
        }
        int isOk;
        try {
            // 调用远程接口发券
            isOk = cardMapper.insertList(cardList);
            // isOk = card2Mapper.batchInsert(toSends) > 0 ? true : false;
            //isOk = apiUtils.postCard(toSends);
            // isOk=true;
            if (isOk > 0) {
                pack.setStatus(1);
                // 更新礼包状态
                giftPackageMapper.updateByPrimaryKeySelective(pack);
                //发短信
                sendSmsByMapInfo(smsInfoMap);
                return Result.createByResultEnum(ResultEnum.POST_CARD_SUCCESS);
            } else {
                return Result.createByResultEnum(ResultEnum.POST_CARD_FAILURE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.POST_CARD_FAILURE);
        }

    }

    public void sendSmsByMapInfo(Map<String, Integer> smsInfoMap) throws ClientException {
        if (smsInfoMap != null) {
            for (Map.Entry<String, Integer> entry : smsInfoMap.entrySet()) {
                AliyunSmsUtils.sendSms2(entry.getKey(), entry.getValue() + "");
            }
        }
    }

}
